from django.http import HttpResponseServerError
from django.http.response import HttpResponseBase
# 导入返回响应
from SaaSDevelTool.data_return_response import create_response
# 导入redis
from SaaSDevelTool.data_redis_link import r


class SaaSDataMiddlewares:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):

        # 定义白名单
        white = [
            "/platform/api/saas/devel/user/login/",
            "/platform/api/saas/devel/api/upload/create/"
        ]
        # 判断当前请求是否在白名单里 request.path:获取当前请求
        if request.path not in white:
            # 如果不存在获取token
            try:
                token = request.headers["Token"]
            except Exception as err:
                return create_response(code=401, msg="无权访问必须携带token", data="")

            token_value = r.get_str(1, f"background_token{token}")

            if not token_value:
                return create_response(code=401, msg="登录状态不正确", data="")
        response = self.get_response(request)
        # 检查响应对象是否合法
        if not isinstance(response, HttpResponseBase):
            # 如果响应对象不合法，返回一个500状态码的响应对象
            return HttpResponseServerError()

        # 返回响应对象
        return response
